package com.yc.cloud.common.oss.utils;

import cn.hutool.core.util.ZipUtil;
import lombok.val;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;
import java.util.Enumeration;

public class MyZipUtils {

    public static void unzip(String zipFilePath, String outputDirPath) throws IOException {
        File zipFile = new File(zipFilePath);
        File outputDir = new File(outputDirPath);

        try (ZipFile zip = new ZipFile(zipFile)) {
            // Ensuring output directory exists
            if (!outputDir.exists() && !outputDir.mkdirs()) {
                throw new IOException("Failed to create output directory " + outputDir);
            }

            Enumeration<ZipArchiveEntry> entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                File outputFile = new File(outputDir, entry.getName());
                // Creating directory structure
                if (entry.isDirectory()) {
                    if (!outputFile.isDirectory() && !outputFile.mkdirs()) {
                        throw new IOException("Failed to create directory " + outputFile);
                    }
                } else {
                    // Ensure parent directories exist
                    File parentDir = outputFile.getParentFile();
                    if (!parentDir.exists() && !parentDir.mkdirs()) {
                        throw new IOException("Failed to create directory " + parentDir);
                    }

                    // Extracting file
                    try (InputStream in = zip.getInputStream(entry);
                         OutputStream out = new FileOutputStream(outputFile)) {
                        IOUtils.copy(in, out);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        val srcZip = "/Users/jackgu/Downloads/fl0108_.zip";
        val dstZiP = "/Users/jackgu/Downloads/test";
        try {
            long startTime = System.currentTimeMillis();
//            MyZipUtils.unzip(srcZip, dstZiP);
            ZipUtil.unzip(srcZip,dstZiP);
            long endTime = System.currentTimeMillis();
            System.out.println(endTime - startTime);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
